package db

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"hobby-mate/middleware/globalLogger"
	"log"
	"os"
	"time"
)

var (
	Db  *gorm.DB
	err error
)

func init() {
	slowLogger := logger.New(
		//将标准输出作为Writer
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			//设定慢查询时间阈值为1ms
			SlowThreshold: 1 * time.Microsecond,
			//设置日志级别，只有Warn和Info级别会输出慢查询日志
			LogLevel: logger.Warn,
		},
	)
	Db, err = gorm.Open(mysql.New(mysql.Config{
		DSN:                       MysqlDb,
		DefaultStringSize:         256,
		DisableDatetimePrecision:  true,
		SkipInitializeWithVersion: false,
	}), &gorm.Config{
		Logger: slowLogger,
	})
	if err != nil {
		globalLogger.Error(map[string]interface{}{
			"connect db failed": err.Error()})
		os.Exit(1)
	}
	if Db.Error != nil {
		globalLogger.Error(map[string]interface{}{"db error": Db.Error})
	}
}
